// overlay_manager.dart
import 'dart:async';
import 'dart:collection' show Queue;

import 'notify_enum.dart' show NotificationType;
import 'package:flutter/material.dart';

/// 通知数据模型
class _NotificationData {
  final String title;
  final String content;
  final String? iconUrl;
  final NotificationType? type;
  final String? targetRoute;

  _NotificationData({
    required this.title,
    required this.content,
    this.iconUrl,
    this.targetRoute,
    this.type = NotificationType.chat,
  });
}

class WebNotify {
  // 单例
  static final WebNotify _instance = WebNotify._internal();
  factory WebNotify() => _instance;
  WebNotify._internal();

  static late GlobalKey<NavigatorState> _navigatorKey;
  // 消息队列，先进先出
  static final Queue<_NotificationData> _queue = Queue();
  // 跟踪当前正在显示的通知（OverlayEntry），确保同一时间只有一个通知处于激活状态，避免通知重叠
  static final List<OverlayEntry> _activeEntries = [];

  // 1. 初始化，绑定全局上下文
  static void initialize(GlobalKey<NavigatorState> navigatorKey) {
    _navigatorKey = navigatorKey;
  }

  // 2. 显示通知（带队列管理）
  static void show({
    required String title,
    required String content,
    String? iconUrl,
    NotificationType? type,
    String? targetRoute,
  }) {
    _queue.add(_NotificationData(
      title: title,
      content: content,
      iconUrl: iconUrl,
      type: type,
      targetRoute: targetRoute,
    ));
    _processNext();
  }

  static void _processNext() {
    if (_queue.isEmpty || _activeEntries.isNotEmpty) return;

    late final OverlayEntry entry;

    entry = OverlayEntry(
      builder: (context) => _NotificationItem(
        data: _queue.first,
        onDismiss: () {
          entry.remove();
          _activeEntries.remove(entry);
          _queue.removeFirst();
          _processNext();
        },
      ),
    );

    _activeEntries.add(entry);
    _navigatorKey.currentState?.overlay?.insert(entry);
  }

  // 关闭所有notify
  static void dismissAll() {
    for (final entry in _activeEntries) {
      entry.remove();
    }
    _activeEntries.clear();
    _queue.clear();
  }
}

/// 单个通知样式
class _NotificationItem extends StatefulWidget {
  final _NotificationData data;
  final VoidCallback onDismiss;

  const _NotificationItem({
    required this.data,
    required this.onDismiss,
  });

  @override
  _NotificationItemState createState() => _NotificationItemState();
}

class _NotificationItemState extends State<_NotificationItem>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<Offset> _positionAnimation;

  final double _width = 200;
  final double _maxHeight = 80;
  final Duration _continue = Duration(seconds: 2);
  @override
  void initState() {
    super.initState();

    // 动画控制器
    _controller = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    //  注意！！！这是整个遮罩的动画
    _positionAnimation = Tween<Offset>(
      begin: const Offset(1, 0), // 右下外起点（x超过1确保完全在屏幕外）
      end: Offset(0, 0), // 动态距离
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeOut,
    ));

    _controller.forward();
    Future.delayed(_continue, () {
      if (mounted) _dismiss();
    });
  }

  // 关闭通知
  void _dismiss() {
    _controller.reverse().then((_) => widget.onDismiss());
  }

  // 单击事件
  void _click() {
    if (mounted) _dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _positionAnimation,
      child: Align(
        alignment: Alignment.bottomRight,
        child: SafeArea(
          bottom: false,
          child: Container(
            margin: const EdgeInsets.all(20),
            //  限制宽高
            constraints: BoxConstraints(
              maxHeight: _maxHeight,
              maxWidth: _width,
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(12)),
              boxShadow: [
                BoxShadow(
                  color: Colors.black12,
                  blurRadius: 12,
                  offset: Offset(0, 4),
                )
              ],
            ),
            child: Material(
              type: MaterialType.transparency,
              child: InkWell(
                borderRadius: BorderRadius.circular(12),
                onTap: _click, // 添加整体点击事件
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 12,
                  ),
                  child: Row(
                    children: [
                      _buildLeadingIcon(),
                      SizedBox(width: 20),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              widget.data.title,
                              style: TextStyle(
                                fontSize: 16,
                                overflow: TextOverflow.ellipsis,
                                color: Colors.black,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            SizedBox(height: 4),
                            Text(
                              widget.data.content,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.close, size: 18),
                        onPressed: _dismiss,
                        color: Colors.grey[600],
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 构建头部图标组件
  Widget _buildLeadingIcon() {
    return widget.data.iconUrl != null
        ? ClipRRect(
            borderRadius: BorderRadius.circular(20),
            child: Image.network(
              widget.data.iconUrl!,
              width: 40,
              height: 40,
              fit: BoxFit.cover,
            ),
          )
        : const Icon(Icons.notifications_none, size: 24);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
